package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"log"
	"time"
	"user-service/basic/config"
	__ "user-service/basic/proto"
	"user-service/handler/model"
	"user-service/pkg"
)

func (s *Server) OrderCreate(_ context.Context, in *__.OrderCreateReq) (*__.OrderCreateResp, error) {
	//判断用户是否存在
	var user model.User
	err := config.DB.Where("id=?", in.UserId).First(&user).Error
	if err != nil {
		return nil, fmt.Errorf("该用户不存在")
	}
	//判断预约项目是否存在
	var reserveStocks model.ReserveStock
	err = config.DB.Where("id=?", in.ReserveStockId).First(&reserveStocks).Error
	if err != nil {
		return nil, fmt.Errorf("该预约项目不存在")
	}
	var pacg model.Package
	err = config.DB.Where("id=?", in.PackageId).First(&pacg).Error
	if err != nil {
		return nil, fmt.Errorf("该套餐不存在")
	}
	if reserveStocks.UsdStock < 500 {
		return nil, fmt.Errorf("预约人数已超过五百,明天再来")
	}
	//判断库存是否充足
	if reserveStocks.RemainingStock < in.Stock {
		return nil, fmt.Errorf("库存不充足")
	}
	//开启事务
	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = tx.Error; err != nil {
		return nil, nil
	}
	if err = reserveStocks.UpdateRemainingStock(config.DB, in.Stock); err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("库存扣减失败")
	}

	//创建订单
	orders := model.Order{
		Model:         gorm.Model{},
		OrderSn:       uuid.NewString(),
		UserId:        in.UserId,
		PackageId:     in.PackageId,
		HospitalId:    reserveStocks.HospitalId,
		ReserveData:   reserveStocks.ReserveDate,
		Amount:        float32(reserveStocks.RemainingStock) * pacg.Price,
		PaymentMethod: 1,
		Stock:         in.Stock,
		Status:        0,
	}
	go func(ordersn string, ReserveStockId, UserId int64) {
		time.Sleep(time.Minute * 30)
		err = reserveStocks.UpdateRemainingStatus(config.DB)
		if err != nil {
			panic("该订单无法取消")
			return
		}
		log.Printf("该订单已取消%d", in.ReserveStockId)
	}(orders.OrderSn, int64(reserveStocks.ID), int64(user.ID))
	if err = config.DB.Create(&orders).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("订单创建失败")
	}
	amount := fmt.Sprintf("%.2f", orders.Amount)
	alipay := pkg.Alipay(uuid.NewString(), amount)
	return &__.OrderCreateResp{
		OrderSn: orders.OrderSn,
		Url:     alipay,
	}, nil
}
func (s *Server) OrderList(_ context.Context, in *__.OrderListReq) (*__.OrderListResp, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var orders []model.Order
	config.DB.Offset(int(offset)).Limit(int(pageSize)).Where("status=?", in.Status).
		Order("created_at desc").Find(&orders)
	var packagelist []*__.OrderList
	for _, m := range orders {
		list := __.OrderList{
			PackageId:  m.PackageId,
			UserId:     m.UserId,
			Stock:      m.Stock,
			OrderSn:    m.OrderSn,
			HospitalId: m.HospitalId,
			Amount:     m.Amount,
		}
		packagelist = append(packagelist, &list)
	}
	return &__.OrderListResp{
		List: packagelist,
	}, nil
}
